# -*- coding: utf-8 -*-
# --------------前端视图------------------
from flask import Response, request, render_template, views, redirect
from blog_setting.myCrypto import *
from flask_wtf import FlaskForm
from .models import *
from flask_admin import BaseView, expose
# 全局的参数
data_obj = {
    'date': time.asctime(), # Thu Jan 12 21:41:34 2023
    'date_year': time.strftime("%Y", time.localtime(time.time())), # 2022
    'Lunar_Calendar': Lunar_Calendar_day(), #获取农历日期，虽然但是转换依然是365天 当前355-> 最多365 , 2022

}


# 赞助名单
class Sponsor_View(views.View):
    def dispatch_request(self):
        # {'url': 'https://img.com/img.png', 'urlimg': 'https://img.com/img.png' ,'name': 'yin', 'mailbox': '248@qq.com', 'money': 100}
        sponsordata = []
        response = Response(render_template('blog/sponsors.html', sponsordata=sponsordata, data_obj=data_obj))
        return response

# 关于页面
class About_View(views.View):
    def dispatch_request(self):
        response = Response(render_template('blog/about.html', data_obj=data_obj))
        return response

# 工具点赞请求
def Tool_View_Praise(id:int):
    Visitorid = Visitor_Add()
    if Visitorid == -1:
        return redirect('https://www.baidu.com/')
    try:
        is_praise = db.session.query(PraiseTool).filter(PraiseTool.tool_page_id == id, PraiseTool.visitor_id == Visitorid).first()
        is_praise.is_praise = 1
        db.session.add(is_praise)
        db.session.commit()
        return redirect('/tools/'+ str(id))
    except:
        return render_template('error/page_403.html')
# 工具内页面
def Tool_View(id:int):
    try:
        Visitorid = Visitor_Add()
        if Visitorid == -1:
            return redirect('https://www.baidu.com/')
        newdby = db.session.query(PraiseTool).filter(PraiseTool.visitor_id == Visitorid, PraiseTool.tool_page_id == id).first()
        if newdby is None :
            articledb = db.session.query(ToolsNetPage).filter(ToolsNetPage.tool_page_id == id).first()
            db.session.add(PraiseTool(visitor_id= Visitorid, tool_page_id=articledb.tool_page_id, is_praise=0))
            db.session.commit()
        newdby = db.session.query(ToolsNetPage).filter(ToolsNetPage.tool_page_id == id).first()
        if newdby is None:
            raise
        eye = db.session.query(PraiseTool).filter(PraiseTool.tool_page_id == id).all()
        is_praise = db.session.query(PraiseTool).filter(PraiseTool.tool_page_id == id, PraiseTool.visitor_id == Visitorid).first()
        is_praise = is_praise.is_praise
        praise = db.session.query(PraiseTool).filter(PraiseTool.tool_page_id == id,
                                                        PraiseTool.is_praise == 1).all()
        wab = {'id': newdby.tool_page_id, 'title': newdby.title, 'content': newdby.content, 'tag': newdby.tag, 'eye': len(eye),
               'praise': len(praise), 'is_praise': is_praise}
        # 相关推荐代码
        newdby = db.session.query(ToolsNetPage).filter(ToolsNetPage.tools_id == newdby.tools_id).order_by(ToolsNetPage.create_time.desc()).limit(6).all()
        tuijian = []
        for i in newdby:
            eye = db.session.query(PraiseTool).filter(PraiseTool.tool_page_id == i.tool_page_id).all()
            praise = db.session.query(PraiseTool).filter(PraiseTool.tool_page_id == i.tool_page_id,
                                                            PraiseTool.is_praise == 1).all()
            tuijian.append({'id': i.tool_page_id, 'name': i.title, 'intor': i.intro, 'tag': i.tag, 'e': len(eye), 'p': len(praise)})
        response = Response(
            render_template('blog/tool.html', id=id, wab=wab, tuijian=tuijian, data_obj=data_obj))
        return response
    except:
        return render_template('error/page_500.html')


# 文章点赞请求
def Article_View_Praise(id:int):
    Visitorid = Visitor_Add()
    if Visitorid == -1:
        return redirect('https://www.baidu.com/')
    try:
        is_praise = db.session.query(PraiseArticle).filter(PraiseArticle.article_id == id, PraiseArticle.visitor_id == Visitorid).first()
        is_praise.is_praise = 1
        db.session.add(is_praise)
        db.session.commit()
        return redirect('/articles/'+ str(id))
    except:
        return render_template('error/page_403.html')
# 文章页面
def Article_View(id:int):
    try:
        Visitorid = Visitor_Add()
        if Visitorid == -1:
            return redirect('https://www.baidu.com/')
        newdby = db.session.query(PraiseArticle).filter(PraiseArticle.visitor_id == Visitorid, PraiseArticle.article_id == id).first()
        if newdby is None :
            articledb = db.session.query(MultiArticle).filter(MultiArticle.article_id == id).first()
            db.session.add(PraiseArticle(visitor_id= Visitorid, article_id=articledb.article_id, is_praise=0))
            db.session.commit()
        newdby = db.session.query(MultiArticle).filter(MultiArticle.article_id == id).first()
        if newdby is None:
            raise
        eye = db.session.query(PraiseArticle).filter(PraiseArticle.article_id == id).all()
        is_praise = db.session.query(PraiseArticle).filter(PraiseArticle.article_id == id, PraiseArticle.visitor_id == Visitorid).first()
        is_praise = is_praise.is_praise
        praise = db.session.query(PraiseArticle).filter(PraiseArticle.article_id == id,
                                                        PraiseArticle.is_praise == 1).all()
        wab = {'id': newdby.article_id, 'title': newdby.title, 'content': newdby.content, 'tag': newdby.tag, 'eye': len(eye),
               'praise': len(praise), 'is_praise': is_praise, 'time': str(newdby.update_time).split(' ')[0]}
        # 相关推荐代码
        newdby = db.session.query(MultiArticle).filter(MultiArticle.class_sub_id == newdby.class_sub_id).order_by(MultiArticle.update_time.desc()).limit(6).all()
        tuijian = []
        for i in newdby:
            eye = db.session.query(PraiseArticle).filter(PraiseArticle.article_id == i.article_id).all()
            praise = db.session.query(PraiseArticle).filter(PraiseArticle.article_id == i.article_id,
                                                            PraiseArticle.is_praise == 1).all()
            tuijian.append({'id': i.article_id, 'name': i.title, 'intor': i.intro, 'tag': i.tag, 'e': len(eye), 'p': len(praise)})
        response = Response(
            render_template('blog/article.html', id=id, wab=wab, tuijian=tuijian, data_obj=data_obj))
        return response
    except:
        return render_template('error/page_500.html')


# 工具页面
def Tools_View(level:str=None):
    Visitor_Add()
    csfub, cswzb= cstwoTrue(ToolsNet, 'tools_id', 'tools_name', ToolsNetPage, 'tool_page_id', PraiseTool)
    response = Response(render_template('blog/tools.html', data_obj=data_obj, level=level, csfub2=csfub, cswzb2=cswzb))
    return response

# 博客页面
def Articles_View(level:int=None, page:int=1):
    def dispatch_request(self):
        Visitorid = Visitor_Add()
        if Visitorid == -1:
            return redirect('https://www.baidu.com/')
    csfub, cswzb= cstwoTrue(MultiClassSub, 'class_sub_id', 'class_sub_name',MultiArticle, 'article_id', PraiseArticle, level, page)
    response = Response(render_template('blog/articles.html', data_obj=data_obj, level=level, page=page, csfub=csfub, cswzb=cswzb))
    return response


# 首页
class Home_View(views.View):
    def dispatch_request(self):
        Visitorid = Visitor_Add()
        if Visitorid == -1:
            return redirect('https://www.baidu.com/')
        data = db.session.query(MultiClassSub).filter(MultiClassSub.class_sub_id > 0).all()
        wenzhang = []
        for md in data:
            datanuw = db.session.query(MultiArticle).filter(MultiArticle.class_sub_id == md.class_sub_id).all()
            num = len(datanuw)
            hot = 0
            for i in datanuw:
                numlistmd = db.session.query(PraiseArticle).filter(PraiseArticle.praise_id > 0,
                                                                PraiseArticle.article_id == i.article_id,
                                                                PraiseArticle.is_praise == 1).all()
                hot += len(numlistmd)

            wenzhang.append({'id': md.class_sub_id, 'name': md.class_sub_name, 'intro': md.intro, 'hot': hot, 'num': num})

        data = db.session.query(ToolsNet).filter(ToolsNet.tools_id > 0).all()
        gongju = []
        for md in data:
            datanuw = db.session.query(ToolsNetPage).filter(ToolsNetPage.tools_id == md.tools_id).all()
            num = len(datanuw)
            hot = 0
            for i in datanuw:
                numlistmd = db.session.query(PraiseTool).filter(PraiseTool.praise_id > 0 ,PraiseTool.tool_page_id == i.tool_page_id, PraiseTool.is_praise == 1).all()
                hot += len(numlistmd)

            gongju.append({'id': md.tools_id, 'name': md.tools_name, 'intro': md.intro, 'hot': hot, 'num': num})
        response = Response(render_template('blog/index.html', data_obj=data_obj, wenzhang= wenzhang, gongju= gongju))
        return response
# 查询数据库返回数据，类型为字典

def cstwoTrue(fub, fubid:str, fubname:str, wzb, wzbid:str, praise, level:int=None, page:int=0):
    """
    :param fub: 父表模型类
    :param fubid: 父表ID
    :param fubname: 父表标题
    :param wzb: 子表模型类
    :param wzbid: 子表ID
    :param praise: 对应的赞表模型
    :param page: 分页可选填
    :return: 字典格式
    """
    sub = db.session.query(fub).filter(fub.__dict__[fubid] > 0).all()
    csfub = []
    for md in sub:
        datanuw = db.session.query(wzb).filter(wzb.__dict__[fubid] == md.__dict__[fubid]).all()
        num = len(datanuw)
        hot = 0
        for i in datanuw:
            numlistmd = db.session.query(praise).filter(praise.praise_id > 0,
                                                            praise.__dict__[wzbid] == i.__dict__[wzbid],
                                                            praise.is_praise == 1).all()
            hot += len(numlistmd)

        csfub.append({'id': md.__dict__[fubid], 'name': md.__dict__[fubname], 'intro': md.intro, 'hot': hot, 'num': num})
    cswzb = []
    for md in sub:
        if level != None:
            if level != md.__dict__[fubid]:
                continue
        datanuw = db.session.query(wzb).filter(wzb.__dict__[fubid] == md.__dict__[fubid]).order_by(wzb.create_time.desc()).limit(10).all()
        if page == 1:
            datanuw = db.session.query(wzb).filter(wzb.__dict__[fubid] == md.__dict__[fubid]).order_by(wzb.create_time.desc()).limit(10).all()
        elif page >1:
            datanuw = db.session.query(wzb).filter(wzb.__dict__[fubid] == md.__dict__[fubid]).order_by(wzb.create_time.desc()).offset(10).limit(10).all()
        for md in datanuw:
            numlistmd = db.session.query(praise).filter(praise.praise_id > 0,
                                                            praise.__dict__[wzbid] == md.__dict__[wzbid],
                                                            praise.is_praise == 1).all()
            numlistmd = len(numlistmd)
            eyenum = db.session.query(praise).filter(praise.praise_id > 0,
                                                         praise.__dict__[wzbid] == md.__dict__[wzbid]).all()
            eyenum = len(eyenum)
            cswzb.append(
                {'id': md.__dict__[wzbid], 'w': md.__dict__[fubid], 'name': md.title, 'intor': md.intro, 'tag': md.tag, 'c': eyenum,
                 'p': numlistmd})
    db.session.close()
    return csfub, cswzb

def get_ipaddr():
    if request.access_route:
        return request.access_route[0]
    else:
        return request.remote_addr or '127.0.0.1'

def Visitor_Add():
    try:
        ua_id = User_ID_IS(get_ipaddr())
        User_Agents = request.headers.get('User-Agent')
        User_Agents_type = User_Agents_Is(User_Agents)
            # TODO: write code...
        if ua_id is None and User_Agents_type is None:
            return -1
        
        Visitordb = db.session.query(Visitor).filter(Visitor.visitor_id_address == ua_id).first()
        if Visitordb is None:
            db.session.add(Visitor(visitor_id_address=ua_id, os_type=User_Agents_type, create_time=Time_Standard(),
                                   region='保留地址'))
            db.session.commit()
            Visitordb = db.session.query(Visitor).filter(Visitor.visitor_id_address == ua_id).first()

        return Visitordb.visitor_id
    except:

        return 0



# --------------后端视图 - -----------------
# 首页
def Backstage_View():
    response = Response(render_template('backstage/index.html'))
    return response
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired
# ...
class LoginForm(FlaskForm):
    """登录表单类"""
    username = StringField('用户名', validators=[DataRequired()])
    password = PasswordField('密码', validators=[DataRequired()])

# 登录页
def Login_View():
    form = LoginForm()
    emsg = ''
    if request.method == "POST" and form.validate_on_submit():
        user_name = form.username.data
        password = form.password.data
        user = db.session.query(BlogUser).filter(BlogUser.login_name == user_name, BlogUser.user_pwd == password, BlogUser.locked == 0 ).first()  # 从用户数据中查找用户记录
        if user is None:
            emsg += ""
            emsg = "用户名或密码密码有误"
        else:
            rep = redirect('/backstage/')
            rep.set_cookie('uun', Encrypt(user.login_name), 60*60*24*365)
            rep.set_cookie('uup', Encrypt(user.user_pwd), 60*60*24*365)
            return rep
    response = Response(render_template('backstage/login.html', form=form, emsg=emsg))
    return response
